﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;

namespace Mahanet.Abyss.PathCalculation
{
	public class TickTimer
	{
		#region Locks

		private object TIMER_LOCK = new object();

		#endregion

		#region Events

		public event Action<int, int> Elapsed;

		#endregion

		#region Fields

		private int m_CurrentTick = 0;
		private int m_FinalTick;
		private Timer m_Timer;

		#endregion
		
		#region C'tor

		public TickTimer(int finalTick, double tickIntervalInMs)
		{
			m_Timer = new Timer(tickIntervalInMs);
			m_Timer.Elapsed += m_Timer_Elapsed;

			m_FinalTick = finalTick;
		}

		#endregion

		#region Public Methods

		public void Start()
		{
			m_Timer.Start();
		}

		public void Stop()
		{
			m_Timer.Stop();
		}

		#endregion

		#region Private Methods

		private void m_Timer_Elapsed(object sender, ElapsedEventArgs e)
		{
			lock (TIMER_LOCK)
			{
				if (m_CurrentTick <= m_FinalTick)
				{
					RaiseElapsedEvent(m_CurrentTick, m_FinalTick);
				}

				if (m_CurrentTick == m_FinalTick)
				{
					m_Timer.Stop();
				}

				m_CurrentTick++;
			}
		}

		private void RaiseElapsedEvent(int tick, int finalTick)
		{
			if (Elapsed != null)
			{
				Elapsed(tick, finalTick);
			}
		}

		#endregion
	}
}
